package cn.qiuyu.gift.service.impl;

import cn.qiuyu.gift.client.LoginUserFeignClient;
import cn.qiuyu.gift.domain.LoginUser;
import cn.qiuyu.gift.domain.User;
import cn.qiuyu.gift.domain.UserInfo;
import cn.qiuyu.gift.dto.PhoneCodeDto;
import cn.qiuyu.gift.dto.UserRegisterDto;
import cn.qiuyu.gift.enums.SystemErrorCode;
import cn.qiuyu.gift.exception.BusinessException;
import cn.qiuyu.gift.mapper.UserInfoMapper;
import cn.qiuyu.gift.mapper.UserMapper;
import cn.qiuyu.gift.service.IUserService;
import cn.qiuyu.gift.util.AjaxResult;
import cn.qiuyu.gift.util.RonghuaAssert;
import cn.qiuyu.gift.util.StrUtils;
import cn.qiuyu.gift.util.VerifyCodeUtils;
import cn.qiuyu.gift.util.encrypt.MD5;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author yaohuaipeng
 * @since 2024-07-20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Autowired
    public UserMapper userMapper;

    @Autowired
    public UserInfoMapper userInfoMapper;

    @Autowired
    public LoginUserFeignClient loginUserFeignClient;



    @Override
    public String createimgcode(String uuid) {
        //生成图形验证码的数字(4位)
        String code = StrUtils.getRandomString(4);
        //放到redis
        redisTemplate.opsForValue().set(uuid,code,5, TimeUnit.MINUTES);
        //把数字转换为图片
        System.out.println("图形验证码"+code);
        try {
            return VerifyCodeUtils.verifyCode(102, 42, code);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    @Override
    public void phonecode(PhoneCodeDto phoneCode) {

        String key = phoneCode.getType()+":"+phoneCode.getPhone();
        //生成手机验证码
        String code = StrUtils.getRandomString(6);

        if (phoneCode.getType().equals("REG")) {
            //验证图形验证码
            Object o = redisTemplate.opsForValue().get(phoneCode.getUuid());
            RonghuaAssert.isNotNull(o, SystemErrorCode.RESPONSE_CODE_500002);
            //图形验证码是否正确
            RonghuaAssert.isEq(phoneCode.getImgCode(),o.toString(),SystemErrorCode.RESPONSE_CODE_500002);
        }

        Object o1 = redisTemplate.opsForValue().get(key);
        if (o1!=null){
            //获取验证码的时间  解决不能1分钟内发多次的问题
            Long aLong = Long.valueOf(o1.toString().split(":")[1]);
            if ((System.currentTimeMillis()-aLong)<60*1000){
                throw new BusinessException(SystemErrorCode.RESPONSE_CODE_500003);
            }
            code=o1.toString().split(":")[0];

        }


        //把验证码存到redis k 手机号 v code
        redisTemplate.opsForValue().set(key,code+":"+System.currentTimeMillis(),5,TimeUnit.MINUTES);

        //发送到手机
//        Boolean aBoolean = SmsUtil.sendMasg(phoneCode.getPhone(), code);

        System.out.println("k的值"+key);
        System.out.println("本次的验证码:"+code);
    }

    @Override
    public void userregister(UserRegisterDto user) {


        checkdata(user);
        LoginUser loginUser = new LoginUser();
        loginUser.setPassword(user.getPasword());
        loginUser.setTel(user.getPhone());
        loginUser.setType(LoginUser.USER_WEB);
        AjaxResult ajaxResult = loginUserFeignClient.addOrUpdate(loginUser);
        RonghuaAssert.isTrue(ajaxResult.getSuccess(),SystemErrorCode.RESPONSE_CODE_400500);
        Long aLong = Long.valueOf(ajaxResult.getData().toString());


        User user1 = new User();
        user1.setCreateTime(System.currentTimeMillis());
        user1.setPhone(user.getPhone());
        user1.setPassword(MD5.getMD5(user.getPasword()));
        user1.setLoginId(aLong);
        userMapper.insert(user1);

        UserInfo userInfo = new UserInfo();
        userInfo.setRegChannel(1);
        userInfo.setRegTime(System.currentTimeMillis());
        userInfo.setUserId(user1.getId());
        userInfoMapper.insert(userInfo);


    }

    private void checkdata(UserRegisterDto user) {

        //1.验证输入的验证码是否正确
        String key = user.getType()+":"+ user.getPhone();
        System.out.println(key);
        Object o = redisTemplate.opsForValue().get(key);
        //判断手机验证码是否正确
        RonghuaAssert.isEq(o.toString().split(":")[0],user.getPhonecode(), SystemErrorCode.RESPONSE_CODE_500002);
        System.out.println(o);
        //是否注册过
        EntityWrapper<User> twrapper = new EntityWrapper<>();
        twrapper.eq("phone",user.getTel());
        Integer integer = userMapper.selectCount(twrapper);
        RonghuaAssert.isZero(integer,SystemErrorCode.RESPONSE_CODE_400004);

    }
}
